package com.sphd.education.fragments;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sphd.education.R;
import com.sphd.education.activitys.HomeSerachActivity;
import com.sphd.education.activitys.SearchCityActivity;
import com.sphd.education.adapter.MyViewPagerAdapter;
import com.sphd.education.info.CityGpsInfo;
import com.sphd.education.info.EducationIntentKey;
import com.sphd.education.interfaces.FragmentInterface;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 主页
 * Created by Administrator on 2015/10/12.
 */
public class HomeFragment extends Fragment implements ViewPager.OnPageChangeListener, View.OnClickListener {
    //    @Bind(R.id.id_tablayout)
//    TabLayout idTablayout;
    @Bind(R.id.id_viewpager)
    ViewPager idViewpager;
    @Bind(R.id.city_text)
    TextView cityText;
    @Bind(R.id.tv_school)
    TextView tvSchool;
    @Bind(R.id.tv_lesson)
    TextView tvLesson;


    @Bind(R.id.layout_lesson)
    RelativeLayout layoutLesson;
    @Bind(R.id.layout_school)
    RelativeLayout layoutSchool;


    private Intent intent;

    private String Tag = "HomeFragement";
    private FragmentInterface fragmentInterface;
    private View rootView;
    // TabLayout中的tab标题
    private String[] mTitles;//标题头
    private MyViewPagerAdapter mViewPagerAdapter;//viewpager的适配器
    private Context context;
    private List<Fragment> mFragments;
    SearchLessonFragment searchLessonFragment;
    SearchSchoolFragment searchSchoolFragment;
    private CityGpsInfo cityGpsInfo;


    public static HomeFragment newInstance(Bundle bundle) {
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(bundle);//传值判断是那个fragment
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_home_layout, container, false);
        context = getContext();
        mFragments = new ArrayList<Fragment>();
        ButterKnife.bind(this, rootView);
        initView();
        return rootView;
    }


    /**
     * 跳转到搜索城市的控件
     */
    @OnClick(R.id.city_text)
    public void setOnClickCityTextView() {
        fragmentInterface.fragmentItemSelected(R.id.city_text);
        ContentValues values = new ContentValues();
        values.put("lastcity", cityGpsInfo.getOthercity());
        DataSupport.update(CityGpsInfo.class, values, cityGpsInfo.getId());
        intent.setClass(context, SearchCityActivity.class);
        startActivityForResult(intent, EducationIntentKey.SEARCHCITY);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        intent = new Intent();
        Log.e(Tag, "onAttach" + "myInfo" + (cityGpsInfo == null));
    }

    @Override
    public void onStart() {
        Log.e(Tag, "onStart");
        super.onStart();
        cityGpsInfo = DataSupport.findLast(CityGpsInfo.class);
        if (!cityGpsInfo.getLastcity().equals(cityGpsInfo.getOthercity())) {
            mFragments.clear();
            initView();
        }
        if (cityGpsInfo.isQiecity()) {
            cityText.setText(cityGpsInfo.getOthercity());
        } else {
            cityText.setText(cityGpsInfo.getLoacalcity());
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.e(Tag, "onDestroyView");
        ButterKnife.unbind(this);
    }

    // 接收activity传递过来的接口子类对象
    public void setCallBack(FragmentInterface fragmentInterface) {
        this.fragmentInterface = fragmentInterface;
    }

    private void initView() {
        Bundle bundle = new Bundle();
        bundle.putString(EducationIntentKey.FLAG, EducationIntentKey.HOMEFLAG);
        searchLessonFragment = SearchLessonFragment.newInstance(bundle);
        searchSchoolFragment = SearchSchoolFragment.newInstance(bundle);
        mFragments.add(searchLessonFragment);
        mFragments.add(searchSchoolFragment);
//        // Tab的标题采用string-array的方法保存，在res/values/arrays.xml中写
        mTitles = getResources().getStringArray(R.array.tab_titles);
        mViewPagerAdapter = new MyViewPagerAdapter(getChildFragmentManager(), mTitles, mFragments);
        idViewpager.setAdapter(mViewPagerAdapter);
//        // 设置ViewPager最大缓存的页面个数
//        idViewpager.setOffscreenPageLimit(2);
//        // 给ViewPager添加页面动态监听器（为了让Toolbar中的Title可以变化相应的Tab的标题）
//        idTablayout.setTabMode(TabLayout.MODE_FIXED);//MODE_FIXED按权重显示MODE_SCROLLABLE按具体大小显示
//        // 将TabLayout和ViewPager进行关联，让两者联动起来
//        idTablayout.setupWithViewPager(idViewpager);
//        idTablayout.setTabTextColors(getResources().getColor(R.color.gray), getResources().getColor(R.color.white));
//        // 设置Tablayout的Tab显示ViewPager的适配器中的getPageTitle函数获取到的标题
//        idTablayout.setTabsFromPagerAdapter(mViewPagerAdapter);
        idViewpager.addOnPageChangeListener(this);
////        idViewpager.setCurrentItem(0);

    }

    /**
     * Viewpage监听
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        Log.e("position1",position+"");

    }

    @Override
    public void onPageSelected(int position) {
      select(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    @Override
    public void onClick(View v) {


    }

    @OnClick(R.id.home_search)
    public void goSearch() {
        intent.setClass(context, HomeSerachActivity.class);
        startActivity(intent);
    }
    @OnClick(R.id.tv_lesson)
    public void goLesson() {
        select(0);
    }
    @OnClick(R.id.tv_school)
    public void goSchool() {
     select(1);
    }

    private void select(int i) {
        idViewpager.setCurrentItem(i);
        switch (i){
            case 0:
                layoutSchool.setBackgroundResource(R.drawable.bg_title);
                layoutLesson.setBackgroundResource(R.color.white);
                tvSchool.setTextColor(getResources().getColor(R.color.white));
                tvLesson.setTextColor(getResources().getColor(R.color.colorPrimary));
                break;
            case 1:
                layoutLesson.setBackgroundResource(R.drawable.bg_title);
                layoutSchool.setBackgroundResource(R.color.white);
                tvLesson.setTextColor(getResources().getColor(R.color.white));
                tvSchool.setTextColor(getResources().getColor(R.color.colorPrimary));
                break;
        }
    }
}
